<?php

namespace App\Factory;

class ParseException
{
    public static function parseException(\Throwable $exception): bool|array
    {
        $annotation = new \ReflectionClass($exception);
        //翻转 成code->constant
        $values = array_flip($annotation->getConstants());
        if (empty($values)) {
            return false;
        }
        //拿到对应的constant
        $constant = $values[$exception->getMessage()];
        //constant反射
        $annotation_text = new \ReflectionClassConstant($exception, $constant);
        //获取属性注释内容
        $comment = $annotation_text->getDocComment();
        try {
            preg_match("/Message\(\'(.*?)\'\)(\\r\\n|\\r|\\n)/U", $comment, $result);
        } catch (\Throwable $e) {
            return false;
        }

        if (false === isset($result[1])) {
            return false;
        }
        return [
            'code' => $exception->getMessage(),
            'message' => $result[1]
        ];
    }
}
